#include "si_toolchain.h"
#include "C8051F330_defs.h"
#include "adc.h"
#include "lib.h"

#define VREF (33)

void Adc_Init(void)
{
	ADC0CN = 0x02;                      // ADC0 disabled, normal tracking,
																		 // conversion triggered on TMR2 overflow

	REF0CN = 0x0A;                      // Enable VREF

	AMX0P     = 0x08;
	AMX0N     = 0x11;

	/* Init ADC	 */
	ADC0CF = ((SYSCLK/3000000)-1)<<3;  // Set SAR clock to 3MHz
	ADC0CF |= 0x01;                     // PGA gain = 1
	ADC0CN =	0X80;
	AD0EN=1; 
}

void Adc_SetPort(int port)
{
		AD0EN	=		0; 
		AMX0P     = port;
		AD0EN	=		1; 
		delay_ms(1);
}

// x10
unsigned int Adc_Read(void)
{
	unsigned int adval;
	unsigned int volts = 0;
	
	AD0BUSY = 1;				     /*  Start ADC 0 conversion                       */
	while (AD0BUSY);			   /*  Wait for conversion                          */
	
	/* Read 0-1024 value in ADC0 */
	adval = ADC0L + (ADC0H << 8);

	volts = (unsigned int)(((adval * VREF * 100UL) >> 10UL) / 100);

	return volts;
}